package com.power.sifa.net.service.impl;

import com.alibaba.fastjson.JSON;
import com.aventrix.jnanoid.jnanoid.NanoIdUtils;
import com.plf.common.exception.BusinessException;
import com.plf.common.utils.CommonUtils;
import com.plf.common.utils.SpringHolder;
import com.plf.common.utils.StringUtil;
import com.power.sifa.approve.model.enumeration.St_attach;
import com.power.sifa.net.dao.Apl_formDao;
import com.power.sifa.net.model.EqproFormTreeNode;
import com.power.sifa.net.model.GeneralBuild;
import com.power.sifa.net.model.SiteTreeBuild;
import com.power.sifa.net.model.SiteTreeBuildItem;
import com.power.sifa.net.model.enumeration.Tp_site;
import com.power.sifa.net.service.Apl_formService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

@Slf4j
@Service
public class Apl_formServiceImpl implements Apl_formService {

    @Resource
    private com.plf.core.base.service.Ha_entityormService ha_entityormService;
    @Resource
    private Apl_formDao apl_formDao;

//    @Autowired
//    private Apl_attach_append_listService apl_attach_append_listService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveFormTreeData(EqproFormTreeNode treeNode) throws Exception {
        List<String> ids = new ArrayList<String>(1) {{
            add(treeNode.getBody().get("id").toString());
        }};
        // 先删除, 后保存
        this.ha_entityormService.removeByFields(treeNode.getClsname(), "id", ids);
        this.ha_entityormService.saveObject(SpringHolder.getBean(treeNode.getClsname()).getClass(), treeNode.getBody().get("id").toString(), treeNode.getBody());
        // 存储子表格, 先删除再存
        if (!StringUtil.isEmpty(treeNode.getTabclsname())) {
            List<String> tabids = new ArrayList<String>(1) {{
                add(treeNode.getBody().get("id").toString());
            }};
            // 删除从表数据
            if (!StringUtil.isEmpty(treeNode.getTabclsname())) {
                if (!StringUtil.isEmpty(treeNode.getRelafield())) {
                    this.ha_entityormService.removeByFields(treeNode.getTabclsname(), treeNode.getRelafield(), tabids);
                } else {
                    throw new BusinessException("从表没有关联字段");
                }
            }

            // 存储子表格
            if (!CollectionUtils.isEmpty((Collection<?>) treeNode.getBody().get("table"))) {
                // 1. 转换成list对应的实体类型
                List<Map<String, Object>> tempList = (List<Map<String, Object>>) treeNode.getBody().get("table");
                Class store = SpringHolder.getBean(treeNode.getTabclsname()).getClass();
                List storelist = JSON.parseArray(JSON.toJSONString(tempList), store);
                // 2. 调用saveAll方法
                Object objService = SpringHolder.getBean(treeNode.getTabclsname() + "ServiceImpl");
                Method method = objService.getClass().getDeclaredMethod("saveAll", List.class);
                method.invoke(objService, storelist);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delFormTreeData(Integer sign, String table, String id) {
        List<String> ids = new ArrayList<String>(1) {{
            add(id);
        }};
        this.ha_entityormService.removeByFields(table, "id", ids);

    }

    @Override
    public List<Map<String, Object>> getSelectTree(String clsname, Map<String, Object> filter) throws Exception {
        // 获取实体类名称
        Object objService = SpringHolder.getBean(clsname + "ServiceImpl");
        Method method = objService.getClass().getDeclaredMethod("findAll");
        List<Object> list = (List) method.invoke(objService);
        List<Map<String, Object>> templist = new ArrayList<>(10);
        for (Object v : list) {
            Map<String, Object> tempMap = JSON.parseObject(JSON.toJSONString(v), Map.class);
            if (1 == (Integer) tempMap.get("deleted") || "1".equals(tempMap.get("deleted"))) {
                continue;
            }
            templist.add(tempMap);
        }
        // 如果有sort字段给list排序
        if (templist.size() > 0 && templist.get(0).get("sortnum") != null) {
            Collections.sort(templist, (o1, o2) -> (int) o1.get("sortnum") > (int) o2.get("sortnum") ? 1 : -1);
        }
        List<Map<String, Object>> treeList = CommonUtils.createTree(templist, "id", "parentid", false, null);
        // 如果配置了过滤条件, 则只过滤顶级节点
        if (!filter.isEmpty()) {
            for (int i = treeList.size() - 1; i >= 0; i--) {
                for (Map.Entry<String, Object> entry : filter.entrySet()) {
                    // 支持配置以逗号分隔的多个条件
                    if (entry.getValue().toString().indexOf(",") > -1) {
                        ArrayList<String> valueArr = new ArrayList(Arrays.asList(entry.getValue().toString().split(",")));
                        String value = treeList.get(i).get(entry.getKey()).toString();
                        // 如果逗号里的条件都不满足才删除
                        if (false == valueArr.contains(value)) {
                            treeList.remove(i);
                            break;
                        }
                    } else {
                        if (!treeList.get(i).get(entry.getKey()).toString().equals(entry.getValue().toString())) {
                            treeList.remove(i);
                            break;
                        }
                    }
                }
            }
        }
        // 如果有sort字段给list排序
        if (treeList.size() > 0 && treeList.get(0).get("sortnum") != null) {
            this.recursionSort(treeList);
        }
        return treeList;
    }

    private void recursionSort(List<Map<String, Object>> treeList) {
        Collections.sort(treeList, new Comparator<Map<String, Object>>() {
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                if (o1.get("children") != null) {
                    recursionSort((List<Map<String, Object>>) o1.get("children"));
                }
                return (int) o1.get("sortnum") > (int) o2.get("sortnum") ? 1 : -1;
            }
        });
    }

    /**
     * 保存到数据库
     *
     * @param apltable
     * @return
     */
    private void saveApl(String apltable, List<Map<String, Object>> data) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        // 1. 先取实体再取方法
        Class nodeClass = SpringHolder.getBean(apltable).getClass();
        apltable = apltable + "ServiceImpl";
        Object objService = SpringHolder.getBean(apltable);
        // 2. 进行转换保存
        Method methodSaveAll = objService.getClass().getDeclaredMethod("saveAll", List.class);
        List saveList = JSON.parseArray(JSON.toJSONString(data), nodeClass);
        methodSaveAll.invoke(objService, saveList);

    }

    /**
     * 根据申请表拼出企业表
     *
     * @param apltable
     * @return
     */
    private String getEntTable(String apltable) {
        String enttable = "ent" + apltable.substring(apltable.indexOf("_"));
        return enttable;
    }

    /**
     * 根据企业表拼出申请表
     *
     * @param apltable
     * @return
     */
    private String getAplTable(String apltable) {
        String enttable = "apl" + apltable.substring(apltable.indexOf("_"));
        return enttable;
    }


    /**
     * 递归进行申请表相关字段的初始化
     *
     * @return
     */
    private void recursionConfig(String applyid, Map<String, List<Map<String, Object>>> resultMap, Map<String, Object> node, String parentid) {

        // 厂区节点特殊处理
        node.put("parentid", parentid);
        switch ((Integer) node.get("sign")) {
            case Tp_site.FAC: {
                node.put("applyid", parentid);
                break;
            }
            case Tp_site.LAB: {
                node.put("facid", parentid);
                break;
            }
            case Tp_site.PLANT: {
                node.put("facid", parentid);
                break;
            }
            case Tp_site.PLANTFUN: {
                node.put("plantid", parentid);
                break;
            }
            default: {
                log.warn("未知的回显节点标记1 -> {}", node.get("sign"));
            }
        }
        // 更新自己节点的id
        String newparentid;
        if ((Integer) node.get("sign") == Tp_site.SITE) {
            newparentid = applyid;
        } else {
            newparentid = applyid + NanoIdUtils.randomNanoId();
            node.put("srcid", Integer.valueOf(node.get("id").toString()));
        }
        node.put("id", newparentid);
        node.put("primaryKey", newparentid);

        // 获取子表格列表
        List<Map<String, Object>> tableList = (List<Map<String, Object>>) node.get("table");
        if (!CollectionUtils.isEmpty(tableList)) {
            for (Map<String, Object> t : tableList) {
                t.put("applyid", applyid);
                t.put("srcid", t.get("id"));
                String sonid = applyid + NanoIdUtils.randomNanoId();
                t.put("id", sonid);
                t.put("primaryKey", sonid);
                t.put("parentid", newparentid);
                switch ((Integer) node.get("sign")) {
                    case Tp_site.FAC: {
                        t.put("facid", newparentid);
                        break;
                    }
                    case Tp_site.LAB: {
                        t.put("labid", newparentid);
                        break;
                    }
                    case Tp_site.PLANT: {
                        t.put("plantid", newparentid);
                        break;
                    }
                    case Tp_site.PLANTFUN: {
                        t.put("funcid", newparentid);
                        break;
                    }
                    default: {
                        log.warn("未知的回显节点标记2 -> {}", node.get("sign"));
                    }
                }
            }
        }
        // 获取子节点列表
        List<Map<String, Object>> childrenList = (List<Map<String, Object>>) node.get("children");

        // 递归继续添加
        if (!CollectionUtils.isEmpty(childrenList)) {
            for (Map<String, Object> sonNode : childrenList) {
                this.recursionConfig(applyid, resultMap, sonNode, newparentid);
            }
        }

        String sign = node.get("sign").toString();
        List<Map<String, Object>> tempTable;
        if (resultMap.get(sign) != null) {
            tempTable = resultMap.get(sign);
        } else {
            tempTable = new ArrayList<>(10);
        }
        tempTable.add(node);
        resultMap.put(sign, tempTable);
    }

    /**
     * 把企业表数据保存到申请表
     */
    private void saveAplTable(String applyid, List<Map<String, Object>> treeList, SiteTreeBuild terrBuild) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        // 1. 添加主从表关联字段
        log.info(treeList.toString());
        Map<String, List<Map<String, Object>>> resultMap = new HashMap<>(16);
        for (Map<String, Object> treeItem : treeList) {
            this.recursionConfig(applyid, resultMap, treeItem, "0");
            break;
        }
        log.info(resultMap.toString());

        // 2. 取得对应的结果集保存
        String sign = String.valueOf(Tp_site.SITE);
        if (resultMap.get(sign) != null) {
            this.saveApl(this.getAplTable(terrBuild.getSitetable()), resultMap.get(sign));
            for (SiteTreeBuildItem v : terrBuild.getTreeBuild()) {
                sign = String.valueOf(v.getSign());
                if (resultMap.get(sign) != null) {
                    this.saveApl(this.getAplTable(v.getTable()), resultMap.get(sign));
                    // 如果当前节点有子表格配置, 保存子表格
                    if (!StringUtil.isEmpty(v.getFromtable())) {
                        List<Map<String, Object>> tableList = new ArrayList<>();
                        for (Map<String, Object> c : resultMap.get(sign)) {
                            List<Map<String, Object>> tempList = (List<Map<String, Object>>) c.get("table");
                            if (!CollectionUtils.isEmpty(tempList)) {
                                tableList.addAll(tempList);
                            }
                        }
                        if (!CollectionUtils.isEmpty(tableList)) {
                            this.saveApl(this.getAplTable(v.getFromtable()), tableList);
                        }
                    }
                }
            }
        }

    }

    /**
     * 读取企业库
     *
     * @param terrBuild
     */
    private List<Map<String, Object>> readEnt(String applyid, SiteTreeBuild terrBuild) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        // 1. 把申请表转换成企业表配置
        terrBuild.setSitetable(this.getEntTable(terrBuild.getSitetable()));
        terrBuild.setIsAdd(false);
        for (SiteTreeBuildItem item : terrBuild.getTreeBuild()) {
            if (item.getSign() == Tp_site.FAC) {
                item.setFarelafield("cornumber");
            }
            item.setTable(this.getEntTable(item.getTable()));
            if (!StringUtil.isEmpty(item.getFromtable())) {
                item.setFromtable(this.getEntTable(item.getFromtable()));
            }
        }
        // 2. 取企业库的树结构
        List<Map<String, Object>> treeList = this.buildSiteTree(terrBuild.getCornumber(), terrBuild);
        // 3. 把企业库的数据复制到申请表
        if (treeList == null) {
            return null;
        }
        this.saveAplTable(applyid, treeList, terrBuild);

        return treeList;
    }


    @Override
    public List<Map<String, Object>> buildSiteTree(String applyid, SiteTreeBuild terrBuild) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        // 是否新增, 新增从企业库初始化数据
        if (terrBuild.getIsAdd()) {
            terrBuild.setApplyid(applyid);
            if (!StringUtil.isEmpty(terrBuild.getCornumber())) {
                List<Map<String, Object>> result = this.readEnt(applyid, terrBuild);
                if (result != null) {
                    return result;
                } else {
                    // 企业库也没有数据初始化一个回去
                    {
                        List<Map<String, Object>> currentList = new ArrayList<>(10);
                        Map<String, Object> siteObj = new HashMap<>();
                        siteObj.put("id", applyid);
                        siteObj.put("status", St_attach.AUDIT);
                        siteObj.put("name", "生产场地");
                        siteObj.put("scopedSlots", new HashMap<String, String>() {{
                            put("title", "title");
                        }});
                        siteObj.put("children", new ArrayList(10));
                        siteObj.put("parentid", 0);
                        siteObj.put("sign", Tp_site.SITE);
                        String apltable = this.getAplTable(terrBuild.getSitetable());
                        Object siteService = SpringHolder.getBean(apltable + "ServiceImpl");
                        Method methodSave = siteService.getClass().getDeclaredMethod("saveOrUpdate", SpringHolder.getBean(apltable).getClass());
                        methodSave.invoke(siteService, JSON.parseObject(JSON.toJSONString(siteObj), SpringHolder.getBean(apltable).getClass()));

                        currentList.add(siteObj);
                        return currentList;
                    }
                }
            } else {
                log.error("新增构造树数据，未传入社会统一信用代码");
                throw new RuntimeException("未传入社会统一信用代码 -> buildSiteTree");
            }
        }
        // 1. 查询生产场地
        Object siteService = SpringHolder.getBean(terrBuild.getSitetable() + "ServiceImpl");
        Method methodFindByid = siteService.getClass().getDeclaredMethod("getById", Serializable.class);
        Object siteOne = methodFindByid.invoke(siteService, applyid);
        Map<String, Object> siteObj;
        if (siteOne != null) {
            siteObj = JSON.parseObject(JSON.toJSONString(siteOne), Map.class);
            siteObj.put("name", "生产场地");
        } else {
            // 企业库没有数据直接返回
            if (terrBuild.getIsAdd() == false) {
                log.warn("cornumber没有数据 -> {}", applyid);
                return null;
            }
            siteObj = new HashMap<>(16);
            siteObj.put("id", applyid);
            siteObj.put("status", St_attach.AUDIT);
            siteObj.put("name", "生产场地");
            Method methodSave = siteService.getClass().getDeclaredMethod("saveOrUpdate", SpringHolder.getBean(terrBuild.getSitetable()).getClass());
            methodSave.invoke(siteService, JSON.parseObject(JSON.toJSONString(siteObj), SpringHolder.getBean(terrBuild.getSitetable()).getClass()));
        }

        Map<String, List<Map<String, Object>>> tempMap = new HashMap<>(16);
        // 2. 父级列表
        List<Map<String, Object>> currentList = new ArrayList<>(10);
        siteObj.put("scopedSlots", new HashMap<String, String>() {{
            put("title", "title");
        }});
        siteObj.put("children", new ArrayList(10));
        siteObj.put("parentid", 0);
        siteObj.put("sign", Tp_site.SITE);
        currentList.add(siteObj);
        tempMap.put(String.valueOf(Tp_site.SITE), currentList);
        if (!CollectionUtils.isEmpty(terrBuild.getTreeBuild())) {
            for (SiteTreeBuildItem item : terrBuild.getTreeBuild()) {
                // 3. 每级节点数据
                if (tempMap.get(item.getParentsign()) != null) {
                    currentList = tempMap.get(item.getParentsign());
                }
                if (CollectionUtils.isEmpty(currentList)) {
                    continue;
                }
                // 数据重载
                List<String> ids = this.loopListByRealfield(currentList, "id");
                currentList = this.apl_formDao.queryBatchList(item.getTable(), item.getFarelafield(), ids);

                // * 新增情况下 会给applyid字段赋值, 如果是器械车间, 里的的prodids 产品需要通过srcid转换一下
                if (!StringUtil.isEmpty(terrBuild.getApplyid()) && item.getSign() == Tp_site.PLANT) {
                    for (Map<String, Object> p : currentList) {
                        if (p.get("prodids") != null) {
                            String[] prodidsArr = ((String) p.get("prodids")).split(",");
                            StringBuilder prodStr = new StringBuilder();
                            for (String prodid : prodidsArr) {
                                prodStr.append(prodid + "_" + terrBuild.getApplyid() + ",");
                            }
                            prodStr.deleteCharAt(prodStr.length() - 1);
                            p.put("prodids", prodStr);
                        }
                    }
                }

                if (!CollectionUtils.isEmpty(currentList)) {
                    // 3.1 是否需要配置子表格
                    Map<String, List<Map<String, Object>>> tableMap = new HashMap<>(16);
                    if (!StringUtil.isEmpty(item.getFromtable())) {
                        ids = this.loopListByRealfield(currentList, "id");
                        List<Map<String, Object>> tableList = this.apl_formDao.queryBatchList(item.getFromtable(), item.getRelafield(), ids);
                        if (!CollectionUtils.isEmpty(tableList)) {
                            tableMap = this.conversionMap(tableList, item.getRelafield());
                        }
                    }
                    // 3.2 给table属性赋值
                    this.addDefaultField(currentList, item.getSign(), tableMap);

                    // 3.3 如果之前存过父级节点的数据, 把自己放到children属性里
                    if (tempMap.get(item.getParentsign()) != null) {
                        List<Map<String, Object>> fatherList = tempMap.get(item.getParentsign());
                        Map<String, List<Map<String, Object>>> listMap = this.conversionMap(currentList, item.getFarelafield());
                        for (Map<String, Object> v : fatherList) {
                            if (listMap.get(v.get("id").toString()) != null) {
                                List<Map<String, Object>> oldChildrenLsit = (List<Map<String, Object>>) v.get("children");
                                List<Map<String, Object>> newChildrenLsit = listMap.get(v.get("id").toString());
                                oldChildrenLsit.addAll(newChildrenLsit);
                                v.put("children", oldChildrenLsit);
                            }
                        }
                    }
                    // 防止有多个子节点, 到后面能再次取出来
                    tempMap.put(item.getSign().toString(), currentList);
                }
            }
        }
        // log.info(JSON.toJSONString(tempMap.get(String.valueOf(Tp_site.SITE))));
        return tempMap.get(String.valueOf(Tp_site.SITE));
    }

    @Override
    public List<Map<String, Object>> getGeneralTree(String applyid, GeneralBuild generalBuild) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        // 如果是新增读企业库, 复制再返回
        List<Map<String, Object>> list = null;
        if (generalBuild.getIsAdd()) {
            List<String> ids = new ArrayList<String>(10) {{
                add(generalBuild.getCornumber());
            }};
            // 查询企业库
            List<Map<String, Object>> entList = this.apl_formDao.queryBatchList(generalBuild.getEnttabl(), "cornumber", ids);

            // 添加主表id关联
            list = new ArrayList<>();
            if (!CollectionUtils.isEmpty(entList)) {
                for (Map<String, Object> v : entList) {
                    Map<String, Object> aplObj = new HashMap<>(16);
                    // 2. 配置企业表和申请表的映射关系
                    for (Map.Entry<String, String> entry : generalBuild.getMaprelation().entrySet()) {
                        if (v.get(entry.getKey()) != null) {
                            aplObj.put(entry.getValue(), v.get(entry.getKey()));
                        }
                    }
                    aplObj.put("srcid", v.get("id"));
                    aplObj.put("id", v.get("id") + "_" + applyid);
                    aplObj.put("applyid", applyid);
                    aplObj.put("status", St_attach.AUDIT);
                    list.add(aplObj);
                }
            }

            // 保存到申请表
            if (!CollectionUtils.isEmpty(list)) {
                this.saveApl(generalBuild.getApltabl(), list);
            }
        } else {
            list = this.apl_formDao.queryListByApplyid(generalBuild.getApltabl(), applyid);
        }
        List<Map<String, Object>> result = new ArrayList<>(10);
        if (!CollectionUtils.isEmpty(list)) {
            for (Map<String, Object> v : list) {
                Map<String, Object> tempmap = new HashMap<>(16);
                for (Map.Entry<String, Object> entry : v.entrySet()) {
                    tempmap.put(entry.getKey().toLowerCase(), entry.getValue());
                }
                // ^1. 新增初始化时, 如果是药品生产产品, 清除生产线字段 (关联不上重新选)
                if (generalBuild.getIsAdd() && "apl_drpro_prod".equals(generalBuild.getApltabl())) {
                    tempmap.put("workshop_name", null);
                }

                result.add(tempmap);
            }
            // 2. 根据sortnum进行排序
            if (null != result.get(0).get("sortnum")) {
                Collections.sort(result, (o1, o2) -> ((Number) (o1.get("sortnum") != null ? o1.get("sortnum") : 0)).intValue() > ((Number) (o2.get("sortnum") != null ? o2.get("sortnum") : 0)).intValue() ? 1 : -1);
            }
        }
        return result;
    }

    @Override
    public Map delGeneralNode(String applyid, String id, String apltable, String enttable) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, BusinessException {
        Object objService = SpringHolder.getBean(apltable + "ServiceImpl");
        Method method = objService.getClass().getDeclaredMethod("removeById", Serializable.class);
        method.invoke(objService, id);

        // 1 调一下同步补正接口
//        this.apl_attach_append_listService.syncAppend(applyid, apltable, id);
        return null;

    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map saveGeneralNode(String apltable, String enttable, Map body) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

        Object objService = SpringHolder.getBean(apltable + "ServiceImpl");
        Method method = objService.getClass().getDeclaredMethod("saveOrUpdate", SpringHolder.getBean(apltable).getClass());
        method.invoke(objService, JSON.parseObject(JSON.toJSONString(body), SpringHolder.getBean(apltable).getClass()));

        // 1 调一下同步补正接口
//        this.apl_attach_append_listService.syncAppend((String) body.get("applyid"), apltable, (String) body.get("id"));
        return body;
    }


    @Override
    public List<Map<String, Object>> getEqTree(String cornumber, SiteTreeBuild terrBuild) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        // 1. 查询生产厂区
        Object siteService = SpringHolder.getBean(terrBuild.getSitetable() + "ServiceImpl");
        Method methodFindByid = siteService.getClass().getDeclaredMethod("getById", Serializable.class);
        Object siteOne = methodFindByid.invoke(siteService, cornumber);
        if (siteOne == null) {
            return null;
        }
        Map<String, Object> siteObj;
        siteObj = JSON.parseObject(JSON.toJSONString(siteOne), Map.class);
        siteObj.put("name", "生产场地");
        Map<String, List<Map<String, Object>>> tempMap = new HashMap<>(16);
        // 2. 父级列表
        List<Map<String, Object>> currentList = new ArrayList<>(10);
        siteObj.put("scopedSlots", new HashMap<String, String>() {{
            put("title", "title");
        }});
        siteObj.put("children", new ArrayList(10));
        siteObj.put("parentid", 0);
        siteObj.put("sign", Tp_site.SITE);
        currentList.add(siteObj);
        tempMap.put(String.valueOf(Tp_site.SITE), currentList);
        if (!CollectionUtils.isEmpty(terrBuild.getTreeBuild())) {
            for (SiteTreeBuildItem item : terrBuild.getTreeBuild()) {
                // 3. 每级节点数据
                if (tempMap.get(item.getParentsign()) != null) {
                    currentList = tempMap.get(item.getParentsign());
                }
                if (CollectionUtils.isEmpty(currentList)) {
                    continue;
                }
                // 数据重载
                List<String> ids = this.loopListByRealfield(currentList, "id");
                currentList = this.apl_formDao.queryBatchList(item.getTable(), item.getFarelafield(), ids);

                if (!CollectionUtils.isEmpty(currentList)) {
                    // 3.1 是否需要配置子表格
                    Map<String, List<Map<String, Object>>> tableMap = new HashMap<>(16);
                    if (!StringUtil.isEmpty(item.getFromtable())) {
                        ids = this.loopListByRealfield(currentList, "id");
                        List<Map<String, Object>> tableList = this.apl_formDao.queryBatchList(item.getFromtable(), item.getRelafield(), ids);
                        if (!CollectionUtils.isEmpty(tableList)) {
                            tableMap = this.conversionMap(tableList, item.getRelafield());
                        }
                    }
                    // 3.2 给table属性赋值
                    this.addDefaultField(currentList, item.getSign(), tableMap);

                    // 3.3 如果之前存过父级节点的数据, 把自己放到children属性里
                    if (tempMap.get(item.getParentsign()) != null) {
                        List<Map<String, Object>> fatherList = tempMap.get(item.getParentsign());
                        Map<String, List<Map<String, Object>>> listMap = this.conversionMap(currentList, item.getFarelafield());
                        for (Map<String, Object> v : fatherList) {
                            if (listMap.get(v.get("id")) != null) {
                                List<Map<String, Object>> oldChildrenLsit = (List<Map<String, Object>>) v.get("children");
                                List<Map<String, Object>> newChildrenLsit = listMap.get(v.get("id"));
                                oldChildrenLsit.addAll(newChildrenLsit);
                                v.put("children", oldChildrenLsit);
                            }
                        }
                    }
                    // 防止有多个子节点, 到后面能再次取出来
                    tempMap.put(item.getSign().toString(), currentList);
                }
            }
        }
        log.info(JSON.toJSONString(tempMap.get(String.valueOf(Tp_site.SITE))));
        return tempMap.get(String.valueOf(Tp_site.SITE));
    }


    /**
     * 添加树节点的默认属性
     *
     * @param currentList
     * @param sign
     * @param tableMap
     */
    private void addDefaultField(List<Map<String, Object>> currentList, Integer sign, Map<String, List<Map<String, Object>>> tableMap) {
        if (sign.equals(Tp_site.FAC)) {
            for (Map<String, Object> v : currentList) {
                v.put("name", v.get("addr"));
                v.put("sign", sign);
                v.put("scopedSlots", new HashMap<String, String>() {{
                    put("title", "title");
                }});
                v.put("children", new ArrayList(10));
                String id = String.valueOf(v.get("id"));
                if (tableMap.get(id) != null) {
                    v.put("table", tableMap.get(id));
                }
            }
        } else {
            for (Map<String, Object> v : currentList) {
                v.put("sign", sign);
                v.put("scopedSlots", new HashMap<String, String>() {{
                    put("title", "title");
                }});
                v.put("children", new ArrayList(10));
                String id = String.valueOf(v.get("id"));
                if (tableMap.get(id) != null) {
                    v.put("table", tableMap.get(id));
                }
            }
        }
    }

    /**
     * 根据关联字段转Map
     *
     * @param tableList
     * @param relafield 父级关联字段
     * @return
     */
    private Map<String, List<Map<String, Object>>> conversionMap(List<Map<String, Object>> tableList, String relafield) {
        Map<String, List<Map<String, Object>>> tableMap = new HashMap<>(16);
        List<Map<String, Object>> tempTable;
        for (Map<String, Object> t : tableList) {
            if (tableMap.get(t.get(relafield).toString()) != null) {
                tempTable = tableMap.get(t.get(relafield).toString());
            } else {
                tempTable = new ArrayList<>(10);
            }
            t.put("parentid", t.get(relafield));
            tempTable.add(t);
            tableMap.put(t.get(relafield).toString(), tempTable);
        }
        return tableMap;
    }

    /**
     * 返回关联字段值的list
     *
     * @param currentList
     * @param relafield
     * @return
     */
    private List<String> loopListByRealfield(List<Map<String, Object>> currentList, String relafield) {
        List<String> ids = new ArrayList<>(10);
        for (Map<String, Object> v : currentList) {
            ids.add(String.valueOf(v.get(relafield)));
        }
        return ids;
    }


    @Override
    public List<Map<String, Object>> queryStdByIds(String table, String ids) {
        String[] idList = ids.split(",");
        return this.apl_formDao.queryStdByIds(table, idList);
    }
}
